package org.neptune.service.service.impl;

import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.neptune.api.request.SeckillRequest;
import org.neptune.api.response.SeckillResponse;
import org.neptune.common.util.RandomUtils;
import org.neptune.service.service.SeckillApiService;
import org.neptune.service.service.SeckillService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author lwl
 * @date 2019/7/18 19:02
 */
@Service
public class SeckillApiServiceImpl implements SeckillApiService {

	private static final Logger logger = LoggerFactory.getLogger(SeckillApiServiceImpl.class);

	@Autowired
	private SeckillService seckillService;

	// 获取可用处理器数量，设置线程池大小
	private static int thread_count = Runtime.getRuntime().availableProcessors();

	// 拒绝策略
	private static ThreadPoolExecutor executor = new ThreadPoolExecutor(thread_count,
			thread_count + 1, 60L, TimeUnit.SECONDS, new LinkedBlockingDeque<Runnable>(1000));

	@Override
	public SeckillResponse seckillActionTest(SeckillRequest seckillRequest) {

		logger.info("process count :{}", thread_count);

		switch (seckillRequest.getFuncType()) {
			case 1:
				this.seckill1(seckillRequest);
				break;
			default:
				break;
		}

		return null;
	}

	private void seckill1(SeckillRequest seckillRequest) {
		for (int i = 0; i < seckillRequest.getSeckillCount(); i++){
			final int t = i;
			executor.execute(() -> {
				Thread.currentThread().setName("seckill--" + t);
				// 新对象，线程安全问题
				SeckillRequest request = new SeckillRequest();
				request.setUserId(RandomUtils.createRandomUUID());
				request.setSeckillId(seckillRequest.getSeckillId());
				seckillService.seckillByAopLimit(request);
			});
		}
	}
}
